//
//  CHJUploadVideo.m
//  
//
//  Created by jiaxuzhou on 2017/12/2.
//

#import "CHJUploadVideo.h"
#import <objc/runtime.h>

@implementation CHJUploadVideo

- (void)dealloc {
    
    [self removeObserverForAllProperties:self options:NSKeyValueObservingOptionNew context:nil];
}

- (id)initWithDB:(NSDictionary *)dbInfo {
    self = [super init];
    if (self) {
        self.title      = [dbInfo objectForKey:@"title"];
        self.filePath   = [dbInfo objectForKey:@"filePath"];
       
        self.width      = [dbInfo objectForKey:@"width"];
        self.height     = [dbInfo objectForKey:@"height"];
   
        self.isFinish       = [dbInfo objectForKey:@"isFinish"];
        self.uploadRequestBlock = [dbInfo objectForKey:@"uploadRequestBlock"];
        
        [self addObserverForAllProperties:self options:NSKeyValueObservingOptionNew context:nil];
        
    }
    return self;
}


- (void)removeObserverForAllProperties:(NSObject *)observer
                               options:(NSKeyValueObservingOptions)options
                               context:(void *)context
{
    unsigned int count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (size_t i = 0; i < count; ++i) {
        NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
        if (![[CHJUploadVideo noObProperties] containsObject:key]) {
            [self removeObserver:observer forKeyPath:key context:context];
        }
    }
    free(properties);
}

- (void)addObserverForAllProperties:(NSObject *)observer
                            options:(NSKeyValueObservingOptions)options
                            context:(void *)context {
    unsigned int count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (size_t i = 0; i < count; ++i) {
        NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
        if (![[CHJUploadVideo noObProperties] containsObject:key]) {
            [self addObserver:observer forKeyPath:key
                      options:options context:context];
        }
    }
    free(properties);
}

+ (NSArray *)noObProperties
{
    return @[@"uploadRequestBlock"];
}

@end
